package de.jmda.fx.node;

import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Parent;

public abstract class Util
{
//	private final static Logger LOGGER = Logger.getLogger(Util.class);
	
	public static Node findNextParentWithType(
			Node node, Class<? extends Node> targetType)
	{
		Node parent = node.getParent();

		while (parent != null)
		{
			if (parent.getClass().equals(targetType))
			{
				return parent;
			}
			
			parent = parent.getParent();
		}

		return null;
	}

	/**
	 * Returns position of <code>node</code> as Point2D in <code>parent</code>.
	 * <code>parent</code> is <b>typically <i>not</i></b> node's direct parent
	 * returned by {@link Node#getParent()} but another parent node in the
	 * hierarchy.
	 *
	 * @param node
	 * @param parent
	 * @return
	 */
	public static Point2D pos2DInParent(Node node, Parent parent)
	{
		double x = 0;
		double y = 0;
		
		Node nextNode = node;

		while ((nextNode != null) && (nextNode != parent))
		{
			Bounds nextBounds = nextNode.getBoundsInParent();

			x += nextBounds.getMinX();
			y += nextBounds.getMinY();

			nextNode = nextNode.getParent();
		}

//		if (nextNode == null)
//		{
//			LOGGER.warn("parent not in same hierarchy as node!?");
//		}
		
		return new Point2D(x, y);
	}

	public static String layoutAsString(Node node)
	{
		return String.format
		(
				"layout x|y [%5.1f|%5.1f]",
				node.getLayoutX(), node.getLayoutY()
		);
	}

	public static String pointAsString(Point2D point)
	{
		return String.format
		(
				"point x|y [%5.1f|%5.1f]",
				point.getX(), point.getY()
		);
	}

	public static String boundsAsString(Bounds bounds)
	{
		return
				String.format
				(
						"bounds " +
						"min x|y [%5.1f|%5.1f] " +
						"max x|y [%5.1f|%5.1f] " +
						"wdth [%5.1f] " +
						"hgth [%5.1f]",
						bounds.getMinX(), bounds.getMinY(),
						bounds.getMaxX(), bounds.getMaxY(),
						bounds.getWidth(),
						bounds.getHeight()
				);
	}
}